package com.yjy.userinfo.controller;


import com.yjy.mybatis.config.MybatisPlusConfig;
import com.yjy.userinfo.entity.UserInfo;
import com.yjy.userinfo.service.IUserInfoService;
import com.yjy.utils.ConsistentHashing;
import com.yjy.utils.SnowFlakeGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yanjy
 * @since 2021-08-05
 */
@RestController
@RequestMapping("/users")
public class UserInfoController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private IUserInfoService userInfoService;

    SnowFlakeGenerator snowFlakeGenerator = new SnowFlakeGenerator(1, 1, 1);

    @PostMapping("/batch")
    public void user(@RequestBody List<UserInfo> userInfos) {
        userInfoService.saveBatch(userInfos);
    }

    @PostMapping
    public void signal(@RequestBody UserInfo userInfo) {
        Long bizId = snowFlakeGenerator.nextId();
        userInfo.setBizId(bizId);

        //一致性hash算法得到目标表
        String table = ConsistentHashing.getServer(bizId.toString());
        logger.info("UserInfoController.signal:{}", table);
        MybatisPlusConfig.TABLE_NAME.set(table);

        userInfoService.save(userInfo);
    }
}
